<template>
  <div>
    <div>
      <div style="margin-bottom: 20px">
        <Col span="5"><Input style="width: 90%;" placeholder="名称" v-model="name"/></Col>
        <Button type="info" @click="init()"><Icon type="md-search"/>搜索</Button>
        <Button type="info"  style="margin-left: 10px" @click="addSubstance"><Icon type="md-add"/>添加</Button>
      </div>
      <template>
        <Table border :columns="columns" :data="data">
          <template slot-scope="{ row, index }" slot="action">
            <Button type="primary" size="small" style="margin-right: 5px" @click="updateSubstance(row)">编辑</Button>
            <Button type="error" size="small" style="margin-right: 5px" @click="deleteSociety(row)">删除</Button>
          </template>
        </Table>
      </template>
    </div>
    <Modal v-model="modal" title="物件" @on-ok="saveSubstance">
      <Form :model="substanceInfo">
        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">名称:</Col>
          <Col span="13" offset="1">
            <Input v-model="substanceInfo.name"></Input>
          </Col>
        </Row>
<!--        <Row style="margin-bottom: 10px">-->
<!--          <Col span="5" style="text-align: right;line-height: 35px">物件编码:</Col>-->
<!--          <Col span="13" offset="1">-->
<!--            <Input v-model="substanceInfo.wj_code"></Input>-->
<!--          </Col>-->
<!--        </Row>-->
        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">物件负责人:</Col>
          <Col span="13" offset="1">
            <Input v-model="substanceInfo.wj_fzr"></Input>
          </Col>
        </Row>
        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">负责人电话:</Col>
          <Col span="13" offset="1">
            <Input v-model="substanceInfo.wj_fzr_phone"></Input>
          </Col>
        </Row>
        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">坐标:</Col>
          <Col span="9" offset="1">
            <Input v-model="substanceInfo.csc_mapjson" disabled></Input>
          </Col>
          <Col span="5" offset="1">
            <Button @click="pickMap">选择</Button>
          </Col>
        </Row>
        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">物件地址:</Col>
          <Col span="13" offset="1">
            <Input v-model="substanceInfo.wj_address"></Input>
          </Col>
        </Row>

        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">备注:</Col>
          <Col span="13" offset="1">
            <Input v-model="substanceInfo.remark"></Input>
          </Col>
        </Row>

        <Row style="margin-bottom: 10px">
          <Col span="5" style="text-align: right;line-height: 35px">物件图片:</Col>
          <Col span="5" offset="1">
            <Upload multiple action="http://120.27.63.37:38081/api/ac/file/fileCommonService/upLoadFiles" :before-upload="beforeUpload">
<!--              <img v-if="imgShow || substanceInfo.wj_img" :src="substanceInfo.wj_img" style="width: 50px;height: 50px;margin-bottom: 20px"/>-->
              <Button icon="ios-cloud-upload-outline" style="margin-bottom: 20px">上传图片</Button>
            </Upload>
          </Col>
          <Col span="5"><button style="height: 30px;width: 70px;" @click="clearUploadedImage">重新上传</button></Col>
        </Row>
        <Row style="margin-bottom: 10px">
          <Col span="5"></Col>
          <Col span="4" v-for="item in imgList" v-bind:key="item">
            <img v-if="imgShow || imgList" :src="item" style="width: 50px;height: 50px;margin-bottom: 20px"/>
          </Col>
        </Row>
      </Form>
    </Modal>
    <Modal v-model="modalMap" fullscreen title="地图选点" @on-ok="pickMapOK">
      <template>
        <div class="amap-page-container">
          <!--     地图     -->
          <el-amap vid="amap10" class="amap-demo" :zoom="zoom" :center="center" :events="events">
            <!--     地图标记     -->
            <el-amap-marker vid="index_center" :position="center"></el-amap-marker>
          </el-amap>
        </div>
        <div class="toolbar">
          <h2>当前选中坐标: [{{ lng }}, {{ lat }}] <span v-if="this.address!=''">地址:</span> {{ address }}</h2>
        </div>
      </template>
    </Modal>
  </div>
</template>

<script>
import { deleteSubstance, findSubstanceList, insertSubstance, updateSubstance } from '@/api/eventlist'
import { createUpLoadFiles, getSign } from '../../../../api/common'
import { getUuid } from '../../../../api/eventlist'

export default {
  name: 'substance',
  props: {
    pickInfo: Object
  },
  data () {
    let self = this
    return {
      imgList: [],
      upPicData: {
        fileName: 'module',
        filePath: 'grid/module'
      },
      imgShow: false,
      name: '',
      columns: [
        {
          title: '名称',
          key: 'name',
          align: 'center'
        },
        {
          title: '物件编码',
          key: 'wj_code',
          align: 'center'
        },
        {
          title: '操作',
          slot: 'action',
          align: 'center'
        }
      ],
      data: [],
      substanceInfo: {},
      modal: false,
      modalMap: false,
      zoom: 16, // 缩放
      address: '',
      lng: 0,
      lat: 0,
      center: [123.4650090000, 41.6772870000],
      events: {
        click (e) {
          let { lng, lat } = e.lnglat
          self.lng = lng
          self.lat = lat
          // 这里通过高德 SDK 完成。
          const geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: 'all'
          })
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              if (result && result.regeocode) {
                self.address = result.regeocode.formattedAddress
                self.$nextTick()
              }
            }
          })
          self.center = [lng, lat]
        }
      },
      severUserInfo: {}
    }
  },
  methods: {
    clearUploadedImage () {
      this.imgList = []
      this.imgShow = false
    },
    pickMap () {
      this.modalMap = true
    },
    pickMapOK () {
      let x = this.lng + ',' + this.lat
      this.substanceInfo.csc_mapjson = x
    },
    init () {
      let data = {
        id: this.pickInfo.id,
        name: this.name
      }
      findSubstanceList(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.data = ret.data.data
        } else {
          this.$Notice.error({
            title: '查询失败',
            desc: ret.data.errmsg
          })
        }
      })
    },
    deleteSociety (e) {
      let data = {
        id: e.id
      }
      deleteSubstance(data).then(ret => {
        if (ret.data.errcode === 0) {
          this.$Notice.success({ title: '删除成功', desc: ret.data.errmsg })
          this.init()
        } else {
          this.$Notice.error({ title: '删除失败', desc: ret.data.errmsg })
        }
      })
    },
    addSubstance () {
      this.substanceInfo = {}
      this.imgShow = false
      this.modal = true
      this.center = this.autoCenter(this.pickInfo.csc_mapjson)
    },
    autoCenter (map) {
      let path = JSON.parse(map)
      let total_lng = 0.0
      let total_lat = 0.0
      path.forEach(arr => {
        total_lng += arr[0]
        total_lat += arr[1]
      })
      let newlng = total_lng / path.length
      let newlat = total_lat / path.length
      let newCenter = [newlng, newlat]
      return newCenter
    },
    updateSubstance (e) {
      this.substanceInfo = {}
      this.substanceInfo = e
      if (e.wj_img) {
        this.imgList = e.wj_img.split(',')
      }
      this.modal = true
    },
    saveSubstance () {
      let wj_img = ''
      this.imgList.forEach(function (item) {
        if (wj_img) {
          wj_img = wj_img + ',' + item
        } else {
          wj_img = item
        }
      })
      if (this.substanceInfo.id === undefined) {
        let data1 = {
          name: this.substanceInfo.name,
          remark: this.substanceInfo.remark,
          wj_code: 'WJ' + '---' + this.severUserInfo.company_code + '---' + getUuid(),
          wj_fzr: this.substanceInfo.wj_fzr,
          wj_fzr_phone: this.substanceInfo.wj_fzr_phone,
          csc_mapjson: this.substanceInfo.csc_mapjson,
          wj_img: wj_img,
          wj_address: this.substanceInfo.wj_address,
          company_code: this.pickInfo.company_code,
          area_id: this.pickInfo.area_id,
          street_id: this.pickInfo.street_id,
          community_id: this.pickInfo.community_id,
          garden_id: this.pickInfo.id
        }
        insertSubstance(data1).then(ret => {
          if (ret.data.errcode === 0) {
            this.$Notice.success({ title: '保存成功', desc: ret.data.errmsg })
            this.init()
          } else {
            this.$Notice.error({ title: '保存失败', desc: ret.data.errmsg })
          }
        })
      } else {
        let data2 = this.substanceInfo
        data2.wj_img = wj_img
        updateSubstance(data2).then(ret => {
          if (ret.data.errcode === 0) {
            this.$Notice.success({ title: '保存成功', desc: ret.data.errmsg })
            this.init()
          } else {
            this.$Notice.error({ title: '修改失败', desc: ret.data.errmsg })
          }
        })
      }
    },
    beforeUpload (file) {
      this.substanceInfo.wj_img = ''
      this.imgShow = false
      var time = new Date().getTime()
      let timeStep = time.toString()
      let that = this
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => {
        let index = reader.result.indexOf('base64,') + 7
        that.upPicData.fileName = that.upPicData.fileName + timeStep + '.' + file.type.substring(6)
        that.upPicData.file = reader.result.substring(index)
        that.upPic(that.upPicData)
      }
      return false
    },
    upPic (obj) {
      var time = new Date().getTime()
      let timeStep = time.toString()
      let param = {
        filePath: obj.filePath,
        fileName: obj.fileName,
        timestamp: timeStep
      }
      getSign(param).then(res => {
        if (res.data.errcode === 0) {
          let url = res.data.data.docking_url
          let params = {
            sign: res.data.data.sign,
            timestamp: timeStep,
            filePath: obj.filePath,
            fileName: obj.fileName,
            file: obj.file
          }
          createUpLoadFiles(url, params).then(res => {
            if (res.data.errcode === 0) {
              this.substanceInfo.wj_img = res.data.data
              this.imgList.push(res.data.data)
              this.imgShow = true
            } else {
              this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
            }
          })
        } else {
          this.$Notice.error({ title: '上传失败', desc: res.data.data.msg })
        }
      })
    }
  },
  mounted () {
    this.severUserInfo = this.$store.state.user.severUserInfo
    this.init()
  }
}
</script>

<style scoped>
.amap-demo {
  height: 600px;
}
/*// 表格滚动条*/
.ivu-table-overflowX {
  overflow-x: hidden;
}

/*// 模态框*/
.item1 {
  height: 42px;
  line-height: 40px;
}

/*// 地图*/
.amap-page-container {
  position: relative;
  width: 100%;
  height: 88%;
}

/*// 地图选点预览工具栏*/
.toolbar {
  display: block;
  text-align: center;
  height: 20px;
  margin-top: 50px;
}
</style>
